import {RouteProp} from '@react-navigation/native';
import {RootStackParamList} from '../../Nav/routes';
import {useEffect, useRef, useState} from 'react';
import {
  Dimensions,
  Image,
  Platform,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  primaryBackgroundColor,
  primaryColor,
  primaryColor2,
  primaryColor3,
  secondaryBorderColor,
  secondaryHoverBackgroundColor,
} from '../../../theme/default';
import {useTranslation} from 'react-i18next';
import {useAccountProvider} from '../../../hooks/useAccountProvider';
import QRCode from 'react-qr-code';
import Clipboard from '@react-native-clipboard/clipboard';
import Toast from 'react-native-toast-message';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import ViewShot, {captureRef} from 'react-native-view-shot';
import Share from 'react-native-share';

type ReceiveViewRouteProp = RouteProp<RootStackParamList, 'Receive'>;
type ReceiveViewNavigationProp = NativeStackNavigationProp<
  RootStackParamList,
  'Receive'
>;
type Props = {
  route: ReceiveViewRouteProp;
  navigation: ReceiveViewNavigationProp;
};

const {width} = Dimensions.get('window');

export default function ReceiveView({route, navigation}: Readonly<Props>) {
  const {tokenInfo} = route.params;
  const {t} = useTranslation();
  const {userInfo} = useAccountProvider();

  const logo = require('../../../assets/appicon/app_icon@48.png');

  const [qrCodeValue, setQrCodeValue] = useState<string | null>(null);
  const [qrBase64, setQrBase64] = useState<string | null>(null);
  const viewRef = useRef<ViewShot | null>(null);

  useEffect(() => {
    return () => {
      setQrCodeValue(null);
      setQrBase64(null);
    };
  }, []);

  useEffect(() => {
    if (userInfo) {
      setQrCodeValue(userInfo.solanaAddress);
    }
  }, [userInfo]);

  useEffect(() => {
    navigation.setOptions({
      title:
        undefined === tokenInfo
          ? t('receive')
          : t('receiveToken', {symbol: tokenInfo.symbol}),
    });
  }, [navigation, tokenInfo]);

  const handleShare = async () => {
    if (qrBase64) {
      const shareOptions = {
        title: 'Share QR Code',
        url: `data:image/png;base64,${qrBase64}`,
        type: 'image/png',
      };

      Share.open(shareOptions)
        .then(res => console.log('Share response:', res))
        .catch(err => console.error('Error sharing:', err));
    } else {
      if (viewRef.current) {
        try {
          const uri = await captureRef(viewRef, {
            format: 'png',
            result: 'base64',
          });

          setQrBase64(uri);

          const shareOptions = {
            title: 'Share QR Code',
            url: `data:image/png;base64,${uri}`,
            type: 'image/png',
          };

          Share.open(shareOptions)
            .then(res => console.log('Share response:', res))
            .catch(err => console.error('Error sharing:', err));
        } catch (error) {
          console.error('Failed to capture view:', error);
        }
      }
    }
  };

  const handleCopy = () => {
    Clipboard.setString(userInfo!.solanaAddress);
    Toast.show({
      type: 'info',
      position: Platform.OS === 'android' ? 'top' : 'bottom',
      text1: t('copied'),
    });
  };

  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: primaryBackgroundColor,
      }}>
      <ViewShot
        ref={viewRef}
        style={{
          width: width - 40,
          paddingVertical: 48,
          borderWidth: 1,
          borderColor: primaryColor,
          borderRadius: 16,
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: secondaryHoverBackgroundColor,
        }}>
        <View
          style={{
            justifyContent: 'center',
            alignItems: 'center',
            // marginTop: 24,
            width: 225,
          }}>
          <Text
            style={{
              color: primaryColor2,
              fontSize: 16,
              fontWeight: '600',
              marginBottom: 24,
            }}>
            {t('qrcodeHint')}
          </Text>
          {qrCodeValue && (
            <View>
              <QRCode
                size={225}
                style={{
                  height: 'auto',
                  maxWidth: '100%',
                  width: '100%',
                }}
                bgColor={secondaryHoverBackgroundColor}
                fgColor={'#FFF'}
                value={qrCodeValue}
                viewBox={`0 0 225 225`}
              />
              <View
                style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'center',
                  backgroundColor: '#FFF',
                  position: 'absolute',
                  width: 40,
                  height: 40,
                  top: '50%',
                  left: '50%',
                  transform: [{translateX: -20}, {translateY: -20}],
                  zIndex: 1000,
                  borderRadius: 8,
                  borderWidth: 1,
                  borderColor: primaryColor3,
                }}>
                <Image
                  source={logo}
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: 8,
                    resizeMode: 'contain',
                  }}></Image>
              </View>
            </View>
          )}
          <Text
            style={{textAlign: 'center', color: primaryColor3, marginTop: 24}}>
            {t('walletAddress')}
          </Text>
          <Text style={{textAlign: 'center', color: '#fff', marginTop: 12}}>
            {userInfo?.solanaAddress}
          </Text>
        </View>
      </ViewShot>
      <View
        style={{
          marginTop: 32,
          width: '100%',
          paddingHorizontal: 32,
          height: 44,
          justifyContent: 'space-between',
          alignItems: 'center',
          flexDirection: 'row',
        }}>
        <TouchableOpacity
          onPress={handleCopy}
          style={{
            width: '48%',
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            borderWidth: 1,
            backgroundColor: secondaryBorderColor,
            borderColor: primaryColor,
            borderRadius: 16,
          }}>
          <Text style={{fontSize: 14, color: primaryColor2, fontWeight: '600'}}>
            {t('copyTitle')}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={handleShare}
          style={{
            width: '48%',
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            borderWidth: 1,
            backgroundColor: secondaryBorderColor,
            borderColor: primaryColor,
            borderRadius: 16,
          }}>
          <Text style={{fontSize: 14, color: primaryColor2, fontWeight: '600'}}>
            {t('shareTitle')}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
